import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:jump_scape/js_data/js_box/js_coin_shop.dart';
import 'package:jump_scape/js_data/js_coin_shop.dart';
import 'package:jump_scape/js_data/js_member.dart';
import 'package:jump_scape/js_ui/js_widget/js_image_view.dart';
import 'package:jump_scape/js_ui/js_widget/js_style.dart';

import '../../js_data/js_box/js_init.dart';
import '../../js_data/js_event.dart';
import '../../js_util/js_cash_payment.dart';
import '../../objectbox.g.dart';
import '../js_dialog/js_loading.dart';

class JsCoinShopActivity extends StatefulWidget {
  static const url = 'coin_shop';
  const JsCoinShopActivity({super.key});

  @override
  State<StatefulWidget> createState() => _JsCoinShopActivity();
}

class _JsCoinShopActivity extends State<JsCoinShopActivity> {
  String _balance = '0';
  final List<CoinShopBox> _list = [];

  JsCashPayment? jsCashPayment;

  @override
  void initState() {
    super.initState();
    JsEventManager.statPage(page: JsEventName.jsNamePurchase);

    _init(isFirst: true);
  }

  _init({required bool isFirst}) async {
    final setting = await JsObjectBox.setting;
    final coinShop = JsObjectBox.coinShopBox.getAll();
    var member = JsObjectBox.memberBox.query(MemberBox_.userId.equals(setting.userId)).build().findFirst();

    _list.addAll(coinShop);
    _balance = member?.balance ?? '0';
    if (_balance.isEmpty) _balance = '0';

    if (mounted) setState(() {});

    if (!isFirst) return;

    final value = await JsCoinShop().getCoinList();

    if (mounted) {
      _list.clear();
      _list.addAll(value);
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () => Future.value(false),
      child: Scaffold(
        body: Stack(
          children: [
            jsImage('assets/image/ic_records_bg.png', width: double.infinity, height: double.infinity, fit: BoxFit.cover),
            Padding(
              padding: EdgeInsets.only(top: ScreenUtil().statusBarHeight),
              child: Row(
                children: [
                  InkWell(
                    onTap: () {
                      if (Navigator.canPop(context)) {
                        Navigator.pop(context);
                      }
                    },
                    child: Container(
                      padding: EdgeInsets.fromLTRB(18.r, 15.r, 18.r, 0),
                      child: jsImage('assets/image/ic_finish.png', width: 64.r, height: 64.r),
                    ),
                  ),
                ],
              ),
            ),
            Container(
              width: double.infinity,
              height: double.infinity,
              margin: EdgeInsets.fromLTRB(26.r, ScreenUtil().statusBarHeight + 40.r, 26.r, 0),
              clipBehavior: Clip.antiAlias,
              decoration: jsShapeRoundT(radius: 200.r, color: Colors.white),
              child: Column(
                children: [
                  jsImage('assets/image/ic_coin_shop.png', width: 109.r, fit: BoxFit.fitWidth, padding: EdgeInsets.only(top: 28.r)),
                  Container(
                    margin: EdgeInsets.fromLTRB(34.r, 28.r, 34.r, 0),
                    clipBehavior: Clip.antiAlias,
                    decoration: jsShapeRound(radius: 20.r, shadows: [
                      BoxShadow(offset: Offset(2.r, 4.r), color: Color(0xFFAE6060).withOpacity(0.12), blurRadius: 5.r),
                    ]),
                    child: Stack(
                      children: [
                        jsImage('assets/image/ic_personal_coins_bg.png', width: double.infinity, fit: BoxFit.fitWidth),
                        Positioned.fill(
                          child: Row(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Expanded(child: jsImage('assets/image/ic_icon_big.png', fit: BoxFit.fitWidth, padding: EdgeInsets.fromLTRB(28.r, 11.r, 37.r, 0))),
                              Container(width: 1.r, height: 40.r, color: Colors.black, margin: EdgeInsets.only(top: 19.r)),
                              Expanded(
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    Text('My Coins', style: jsTextStyle(font: JsTextFont.October_Devanagari_Medium, fontColor: Colors.black, fontSize: 12.r)),
                                    SizedBox(height: 5.r),
                                    Text(_balance, style: jsTextStyle(font: JsTextFont.October_Devanagari_Medium, fontColor: Colors.black, fontSize: 20.r)),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                  Expanded(
                    child: GridView.builder(
                      padding: EdgeInsets.fromLTRB(18.r, 30.r, 16.r, 20.r),
                      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                        crossAxisCount: 2,
                        mainAxisSpacing: 18.r,
                        crossAxisSpacing: 17.r,
                        childAspectRatio: 134.0 / 113.0,
                      ),
                      itemCount: _list.length,
                      itemBuilder: (context, index) {
                        final coinShop = _list[index];
                        var isHot = false;
                        var isBigDeal = false;
                        if ((coinShop.tags?.isNotEmpty ?? false) && 'null' != coinShop.tags) {
                          isHot = coinShop.tags?.toLowerCase().contains("hot") ?? false;
                          isBigDeal = !isHot;
                        }

                        return InkWell(
                          child: Stack(
                            children: [
                              Container(
                                width: double.infinity,
                                height: double.infinity,
                                margin: EdgeInsets.only(top: 13.r, right: isHot ? 1.r : 2.r),
                                decoration: jsShapeRound(radius: 10.r, color: Color(0xFFF8F8F8)),
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    Row(
                                      mainAxisAlignment: MainAxisAlignment.center,
                                      crossAxisAlignment: CrossAxisAlignment.end,
                                      children: [
                                        jsImage('assets/image/ic_icon_big.png', width: 42.r, fit: BoxFit.fitWidth, padding: EdgeInsets.only(right: 10.r)),
                                        Column(
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: [
                                            Text(coinShop.exchangeCoin, style: jsTextStyle(font: JsTextFont.October_Devanagari_Medium, fontColor: Colors.black, fontSize: 16.r)),
                                            SizedBox(height: 3.r),
                                            Text(coinShop.getDiscount(), style: jsTextStyle(font: JsTextFont.October_Devanagari_Medium, fontColor: Color(0xFF39D2F9), fontSize: 6.r)),
                                          ],
                                        )
                                      ],
                                    ),
                                    SizedBox(height: 10.r),
                                    Row(
                                      mainAxisAlignment: MainAxisAlignment.center,
                                      children: [
                                        Text(coinShop.getPrice(), style: jsTextStyle(font: JsTextFont.October_Devanagari_Medium, fontColor: Colors.black, fontSize: 13.r)),
                                        if (coinShop.getOriginalPrice().isNotEmpty) SizedBox(width: 17.r),
                                        if (coinShop.getOriginalPrice().isNotEmpty)
                                          Text(
                                            coinShop.getOriginalPrice(),
                                            style: jsTextStyle(
                                              font: JsTextFont.October_Devanagari_Medium,
                                              decoration: TextDecoration.lineThrough,
                                              decorationColor: Colors.black.withOpacity(0.5),
                                              decorationThickness: 1.r,
                                              fontColor: Colors.black.withOpacity(0.5),
                                              fontSize: 10.r,
                                            ),
                                          ),
                                      ],
                                    ),
                                  ],
                                ),
                              ),
                              Align(
                                alignment: Alignment.topRight,
                                child: isHot
                                    ? jsImage('assets/image/ic_coin_shop_hot.png', width: 45.r, fit: BoxFit.fitWidth)
                                    : isBigDeal
                                        ? jsImage('assets/image/ic_coin_shop_big_deal.png', width: 47.r, fit: BoxFit.fitWidth)
                                        : SizedBox(width: 0, height: 0),
                              )
                            ],
                          ),
                          onTap: () {
                            JsEventManager.statPage(page: JsEventName.jsNameCreateorder);

                            jsShowLoadingDialog(context);

                            JsCoinShop().recharge(
                              goodsCode: coinShop.code,
                              onSuccess: (orderNo) {
                                jsCashPayment = JsCashPayment(
                                  onSuccess: ((String payload, String transactionId) {
                                    JsCoinShop().checkRecharge(
                                      orderNo: orderNo,
                                      payload: payload,
                                      transactionId: transactionId,
                                      onSuccess: () {
                                        jsCashPayment?.onClose();

                                        JsMember().synchronizationMember(
                                          onSuccess: (member) {
                                            Navigator.pop(context);

                                            _init(isFirst: false);
                                          },
                                          onFailed: (msg) async {
                                            await Future.delayed(1.seconds);

                                            JsMember().synchronizationMember(
                                              onSuccess: (member) {
                                                Navigator.pop(context);

                                                _init(isFirst: false);
                                              },
                                              onFailed: (msg) async {
                                                await Future.delayed(2.seconds);

                                                JsMember().synchronizationMember(
                                                  onSuccess: (member) {
                                                    Navigator.pop(context);

                                                    _init(isFirst: false);
                                                  },
                                                  onFailed: (msg) {
                                                    Navigator.pop(context);
                                                  },
                                                );
                                              },
                                            );
                                          },
                                        );
                                      },
                                      onFailed: (msg) {
                                        Navigator.pop(context);
                                        jsCashPayment?.onClose();

                                        if (msg.isNotEmpty) {
                                          ScaffoldMessenger.of(context).showSnackBar(
                                            SnackBar(
                                              content: Text(msg, style: jsTextStyle(font: JsTextFont.PoetsenOne, fontColor: Colors.white, fontSize: 20.r)),
                                            ),
                                          );
                                        }
                                      },
                                    );
                                  }),
                                  onFailed: ((bool isCancel, String msg) {
                                    Navigator.pop(context);
                                    jsCashPayment?.onClose();

                                    if (!isCancel && msg.isNotEmpty) {
                                      ScaffoldMessenger.of(context).showSnackBar(
                                        SnackBar(
                                          content: Text(msg, style: jsTextStyle(font: JsTextFont.PoetsenOne, fontColor: Colors.white, fontSize: 20.r)),
                                        ),
                                      );
                                    }
                                  }),
                                );
                                jsCashPayment?.buyProduct(coinShop.code);
                              },
                              onFailed: (msg) {
                                Navigator.pop(context);

                                if (msg.isNotEmpty) {
                                  ScaffoldMessenger.of(context).showSnackBar(
                                    SnackBar(
                                      content: Text(msg, style: jsTextStyle(font: JsTextFont.PoetsenOne, fontColor: Colors.white, fontSize: 20.r)),
                                    ),
                                  );
                                }
                              },
                            );
                          },
                        );
                      },
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
